package io.xxx.xbutler.core.check;

import io.xxx.xbutler.constant.Formats;
import io.xxx.xbutler.domain.RoomCategory;
import io.xxx.xbutler.domain.Store;
import io.xxx.xbutler.domain.task.PushContext;
import io.xxx.xbutler.domain.task.Task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Objects;

@Slf4j
@Order(20)
@Component
public class StoreChecker implements Checker {

    @Value("${push.buffer-time:30}")
    private Integer bufferTime;

    @Override
    public CheckError check(PushContext context) {
        Task task = context.getTask();
        Store store = context.getStore();
        Long storeId = store.getId();

        if (!store.getStatus().equals("NORMAL")) {
            CheckError error = CheckError.StoreStatusNotNormal;
            log.warn("{}[taskId:{}, storeId:{}, storeCode:{}, storeStatus:{}]", error.getErrorMessage(), task.getId(), storeId, store.getCode(), store.getStatus());
            return error;
        }

        if (!Objects.equals(task.getAreaId(), store.getAreaId())) {
            CheckError error = CheckError.StoreAreaNotMatch;
            log.info("{}[taskId:{}, storeId:{}, storeCode:{}, taskAreaId:{}, storeAreaId:{}]", error.getErrorMessage(), task.getId(), storeId, store.getCode(), task.getAreaId(), store.getAreaId());
            return error;
        }

        // 检查门店截单时间
        LocalTime closeTime = store.getCloseTime().minusMinutes(bufferTime);
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(LocalDateTime.of(now.toLocalDate(), closeTime))) {
            CheckError error = CheckError.StoreClosed;
            log.info("{}[taskId:{}, storeId:{}, storeCode:{}, currentTime:{}, storeCloseTime:{}]", error.getErrorMessage(), task.getId(), storeId, store.getCode(), now.format(Formats.DATETIME_FORMATTER), closeTime.format(Formats.DATETIME_FORMATTER));
            return error;
        }

        return null;
    }

    @Override
    public boolean supports(PushContext context) {
        Task task = context.getTask();
        return task.getRoomCategory() == RoomCategory.CustomerRoom || task.getStoreId() != null;
    }
}
